<?php

/**
 * DynamicAddressForm
 * 
 * Form class that can dynamically display multiple embedded address forms
 * 
 * @author Maximilian Lenkeit <dev@lenki.com>
 */
class DynamicAddressForm extends sfForm
{
  
  const OPTION_ALLOW_EMPTY = 'allow_empty';
  const OPTION_POST_VALIDATOR = 'post_validator';
  
  /**
   * Address owning entity
   * @var MultiAddressPossessorInterface
   */
  protected $entity;

  function __construct (MultiAddressPossessorInterface $entity, $options = array())
  {
    $this->entity = $entity;
    parent::__construct(array(), $options);
  }

  public function configure ()
  {
    foreach ($this->entity->getAddresses() as $address)
    {
      $this->addForm($address);
    }
    if (count($this->entity->getAddresses()) == 0)
    { // TODO Remove this for dynamic
      $this->addForm();
    }
    //		$this->addForm(); // TODO Uncomment this for dynamic
    

    if ($this->getOption(self::OPTION_POST_VALIDATOR, true))
    {
      $post_validator = new EmbeddedAddressValidatorSchema();
      $post_validator->setOption(EmbeddedAddressValidatorSchema::OPTION_ALLOW_EMPTY, $this->getOption(self::OPTION_ALLOW_EMPTY, false));
      $this->mergePostValidator($post_validator);
    }
  }

  public function addForm (Address $address = null, $num = null)
  {
    if (is_null($num))
    {
      $num = $this->getNumEmbeddedForms();
    }
    $form = new EmbeddedAddressForm($address);
    $this->embedForm($num, $form);
  }

  public function getNumEmbeddedForms ()
  {
    return count($this->embeddedForms);
  }
}